//
//  ZGLPhotoVC.m
//  Faker
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLPhotoVC.h"
#import "RFQuiltLayout.h"
#import "ZGLWaterCell.h"
#import "ZGLPicVCModel.h"
#import "ZGLShowCollectionVC.h"
#import "ZGLNaviView.h"
#import <MJRefresh.h>
#import "ZGLHTTPTOOL.h"

@interface ZGLPhotoVC () <RFQuiltLayoutDelegate, UICollectionViewDataSource, UICollectionViewDelegate> 

@property (nonatomic, strong) UICollectionView *waterPhoto;
@property (nonatomic, strong) ZGLNaviView *titleView;
@property (nonatomic, strong) NSMutableDictionary *signDic;
@property (nonatomic, strong) NSMutableArray *signArr;

@end

@implementation ZGLPhotoVC

- (void)dealloc {
    _waterPhoto.delegate = nil;
    _waterPhoto.dataSource = nil;
    [_titleView.backButton removeTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];

}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        self.signArr = [userDefaults arrayForKey:@"currentArr"].mutableCopy;
    }
    return self;
}





#pragma mark - 上拉刷新
- (void)setHeaderRefresh {
    self.waterPhoto.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.waterPhoto.header beginRefreshing];
        [self handleData];
        
    }];
}
- (void)handleData {
    [ZGLHTTPTOOL GETWithURL:_yuanUrl withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
        _urlStr = result[@"data"][@"info"][@"next_url"];
        NSMutableArray *arr = result[@"data"][@"articles"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in arr) {
            ZGLPicVCModel *model  = [ZGLPicVCModel modWithDic:dict];
            [modelArr addObject:model];
        }
        _photoArr = modelArr;
        [_waterPhoto reloadData];
        [_waterPhoto.header endRefreshing];
    } withFail:^(id result) {

    }];
}

#pragma mark - 下拉加载
- (void)setFooterRefresh {
    _waterPhoto.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       
        [ZGLHTTPTOOL GETWithURL:_urlStr withBody:nil withHttpHead:nil responseStyle:JSON withSuccess:^(id result) {
            _urlStr = result[@"data"][@"info"][@"next_url"];
            NSMutableArray *arr = result[@"data"][@"articles"];
            NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dict in arr) {
                ZGLPicVCModel *model  = [ZGLPicVCModel modWithDic:dict];
                [modelArr addObject:model];
            }
            for (ZGLPicVCModel *model in modelArr) {
                [_photoArr addObject:model];
            }
           
            [_waterPhoto reloadData];

        } withFail:^(id result) {

        }];
        [_waterPhoto.footer endRefreshing];

    }];
}











- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = backColor;
    _waterPhoto.backgroundColor = backColor;
    _titleView.backgroundColor = naviColor;
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
}

- (void)setNavigationBar {
    _titleView = [[ZGLNaviView alloc] initWithFrame:CGRectMake(0, 0, ScaleX * 375, 64)];
    [_titleView.downButton setImage:[UIImage imageNamed:@"xingqu"] forState:(UIControlStateNormal)];
    [_titleView.downButton addTarget:self action:@selector(downButton:) forControlEvents:(UIControlEventTouchUpInside)];
    _titleView.shareButton.hidden = YES;
    [_titleView.backButton addTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [_titleView.downButton setEnabled:NO];
    [self.view addSubview:_titleView];
}
- (void)backButton:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)downButton:(UIButton *)button {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:_yuanDic[@"title"] forKey:@"title"];
    [dic setObject:_yuanDic[@"large_pic"] forKey:@"large_pic"];
    [dic setObject:_yuanDic[@"block_color"] forKey:@"block_color"];
    [dic setObject:_yuanDic[@"api_url"] forKey:@"api_url"];
    [dic setObject:_yuanDic[@"data_type"] forKeyedSubscript:@"data_type"];
    [self.signArr addObject:dic];
    [userDefaults setObject:_signArr forKey:@"currentArr"];
    [userDefaults synchronize];
    [self subWarning];
}

- (void)setYuanDic:(NSDictionary *)yuanDic {
    if (_yuanDic != yuanDic) {
        _yuanDic = yuanDic;
    }
    for (NSDictionary *dic in _signArr) {
        if ([yuanDic[@"title"] isEqualToString:dic[@"title"]]) {
            [_titleView.downButton setEnabled:NO];
            break;
        } else {
            [_titleView.downButton setEnabled:YES];
        }
    }
}

- (void)subWarning {
    [_titleView.downButton setEnabled:NO];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已订阅" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

- (void)createCollectionView {
    RFQuiltLayout *layout = [[RFQuiltLayout alloc] init];
    //滑动方向
    layout.direction = 0;
    //属性
    layout.blockPixels = CGSizeMake(self.view.frame.size.width / 3, self.view.frame.size.width / 3);
    layout.delegate = self;
    _waterPhoto = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 20) collectionViewLayout:layout];
    _waterPhoto.delegate = self;
    _waterPhoto.dataSource = self;
    [_waterPhoto registerClass:[ZGLWaterCell class] forCellWithReuseIdentifier:@"ceklk"];
    [self.view addSubview:_waterPhoto];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)setPhotoArr:(NSMutableArray *)photoArr {
    if (_photoArr != photoArr) {
        _photoArr = photoArr;
    }
    [self.waterPhoto reloadData];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ZGLShowCollectionVC *showVC = [[ZGLShowCollectionVC alloc] init];
    showVC.photoModel = _photoArr[indexPath.item];
    [self.navigationController pushViewController:showVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createCollectionView];
    [self setNavigationBar];
    [self setHeaderRefresh];
    [self setFooterRefresh];
    // Do any additional setup after loading the view.
}


#pragma mark - collectionViewdelegate & datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_photoArr.count == 0) {
        [self.waterPhoto.footer setFrame:CGRectMake(ScaleX * 87.5, ScaleY * 5, ScaleY * 200, 44)];
        self.waterPhoto.footer.backgroundColor = backColor;
        self.waterPhoto.footer.layer.cornerRadius = 10;
        self.waterPhoto.footer.layer.masksToBounds = YES;
        self.waterPhoto.footer.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.waterPhoto.footer.layer.borderWidth = 1.0f;

        return 5;
    }
    return _photoArr.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGLWaterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ceklk" forIndexPath:indexPath];
    if (_photoArr.count > 0) {
        cell.photoModel = _photoArr[indexPath.item];
    }
    return cell;
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

- (CGSize)blockSizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    //判断下标 由下标改变item的尺寸大侠
    if (indexPath.row % 10 == 0)
        return CGSizeMake(2, 2);
    if (indexPath.row % 11 == 0)
        return CGSizeMake(1, 1);
    else if (indexPath.row % 7 == 0)
        return CGSizeMake(2, 2);
    else if (indexPath.row % 8 == 0)
        return CGSizeMake(1, 1);
    else if(indexPath.row % 11 == 0)
        return CGSizeMake(2, 2);
    if (indexPath.row == 0)
        return CGSizeMake(5, 5);
    
    return CGSizeMake(1, 1);
    
    
}

- (UIEdgeInsets)insetsForItemAtIndexPath:(NSIndexPath *)indexPath {
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
